import 'dart:async';
import 'dart:io';

import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

class InAppPurchaseManager {
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<ProductDetails> _products = [];
  Function? onPurchaseUpdated;
  InAppPurchaseManager() {
    _subscription = _inAppPurchase.purchaseStream.listen(
      _listenToPurchaseUpdated,
      onDone: () => _subscription.cancel(),
      onError: (error) {
        print('error1');
        onPurchaseUpdated?.call({"status": "error", "data": error});
      },
    );
  }

  Future<void> initialize(_kProductIds) async {
    // 初始化支付信息
    await _initStoreInfo(_kProductIds);
  }

  Future<void> _initStoreInfo(_kProductIds) async {
    // 查询产品详情等
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      print('商店连接不上');
      return;
    }
    // if (Platform.isIOS) {
    //   final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
    //       _inAppPurchase
    //           .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
    //   await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    // }
    ProductDetailsResponse productDetailResponse =
        await _inAppPurchase.queryProductDetails(_kProductIds.toSet());
    if (productDetailResponse.error != null) {
      print(productDetailResponse.error);
      return;
    }
    if (productDetailResponse.productDetails.isEmpty) {
      print('没有商品');
      return;
    }
    _products = productDetailResponse.productDetails;
  }

  void _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    final sortedList = List.from(purchaseDetailsList);
    sortedList.sort((a, b) => (int.tryParse(b.transactionDate ?? '') ?? 0)
        .compareTo(int.tryParse(a.transactionDate ?? '') ?? 0));
    for (final PurchaseDetails purchaseDetails in sortedList) {
      // 处理购买状态
      if (purchaseDetails.status == PurchaseStatus.pending) {
        print('loading');
        // onPurchaseUpdated?.call({"status": "loading", "data": purchaseDetails});
      } else if (purchaseDetails.status == PurchaseStatus.purchased ||
          purchaseDetails.status == PurchaseStatus.restored) {
        if (purchaseDetails.pendingCompletePurchase) {
          var appstoreDetail = purchaseDetails as AppStorePurchaseDetails;
          _inAppPurchase.completePurchase(purchaseDetails);
          // print(
          //     'complete1 ${appstoreDetail.productID} ${purchaseDetails.status}');

          //  workData(purchaseDetailsList);
          // print('complete ${appstoreDetail.productID}');
          //
          onPurchaseUpdated?.call({
            "status": "complete",
            "receipt_data":
                purchaseDetails.verificationData.serverVerificationData
          });
        }
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        print('error');
        onPurchaseUpdated?.call({"status": "error", "data": purchaseDetails});
      }
    }
  }

  void _handleError(Object error) {
    print('处理错误');
    // 处理错误
  }

  Future<void> buyProduct(String productId) async {
    // 购买产品逻辑
    try {
      if (!_products.isNotEmpty) {
        return;
      }
      print(productId);

      ProductDetails productDetails = _getProduct(productId);
      _inAppPurchase.buyConsumable(
          purchaseParam: PurchaseParam(productDetails: productDetails));
    } catch (e) {
      print('错误 ${e}');
    }
  }

  ProductDetails _getProduct(String productId) {
    return _products.firstWhere((product) => product.id == productId);
  }

  Future<void> restorePurchases() async {
    await _inAppPurchase.restorePurchases();
  }

  void dispose() {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }
    _subscription.cancel();
  }
}

class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
